from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests
from utils.myredis import r
from models.models import *

left_blue = Blueprint("leftblue",__name__)

# @left_blue.route("/getkind")
# # 获取顶级父类
# def getkind():
#     kinds = db.session.execute("select b.*,a.name as pname,a.id as pid from kind as a left join kind as b on a.id=b.type where a.type=0")
#     kind_lst = []
#     idss = []
#     kinds = list(kinds)
#     if kinds:
#         for i in kinds:
#             # 判断父类是否存在，不存在添加
#             if i.pname not in idss:
#                 idss.append(i.pname)
#                 kind_lst.append({
#                     "id":i.pid,
#                     "name":i.pname,
#                     "son":[{
#                         "name":i.name,
#                         "id":i.id,
#                         "type":i.type
#                     }]
#                 })
#             else:
#                 # 存在，查找父类，遍历父类用子类的pid对比
#                 for (index,p) in enumerate(kind_lst):
#                     if i.pid == p["son"][0]["type"]:
#                         # 将子类加到父类下
#                         kind_lst[index]['son'].append({"id": i.id, "name": i.name})
#     return jsonify({"code": 200, "msg": "获取成功","data":kind_lst})

@left_blue.route("/getkind")
# 页面分类
def getkind():
    kind = Kind.query.all()
    kind_list = []
    reslist = []
    # 读取列表中的每一个放到字典
    dict = {}
    for i in kind:
        reslist.append({
            "value":i.id,
            "label":i.name,
            "type":i.type
        })
    for s in reslist:
        k = s["value"]
        dict[k] = s
    # 判断子类属于那个父类，放到父类的son中
    for j in reslist:
        type = j["type"]
        if type == 0:
            kind_list.append(j)
        else:
            if  "children" not in dict[type]:
                dict[type]["children"] = []
            dict[type]["children"].append(j)
    return jsonify({"code":200,"msg":"获取成功","data":kind_list})

# 需求大厅无限极递归
@left_blue.route("/gettype")
def gettype():
    ids = request.args.get("ids")
    # 获取pid在传递过来的标签id中的id
    sql = 'select id from type where pid in ('+str(ids)+")"
    res = db.session.execute(sql)
    if res:
        idb = []
        for i in res:
            idb.append(i.id)    # 4,5,
        # idslist = idb.split(",")     # ['4', '5', '']
        # print("idslist",idslist)
        # data = idslist[0:-1]
        # strlist = ","
        # idb = strlist.join(data)     # 4,5
        tlst = []
        for i in list(idb):
            if i != ",":
                tt = Type.query.filter_by(id=i).first()
                tlst.append({
                    "id":tt.id,
                    "name":tt.name
                })
        return jsonify({"code":200,"data":tlst})
    return jsonify({"code": 200, "data": ids})


# 无限递归
@left_blue.route('/gettypes')
def gettypes():
    type1 = Type.query.all()
    list1=[]
    rlist = []
    dict = {}
    for i in type1:
        list1.append({'id':i.id,'name':i.name,'pid':i.pid})
    for i in list1:
        k = i['id']
        dict[k] =i

    for j in list1:
        pid = j['pid']
        if pid == 0:
            rlist.append(j)
        else:
            if 'son' not in dict[pid]:
                dict[pid]['son']=[]
            dict[pid]['son'].append(j)
    return jsonify({'code':200,'list':rlist})

# es实现搜索
from elasticsearch import Elasticsearch
# 101.43.203.222  腾讯云    9200:端口
es = Elasticsearch(hosts="http://101.43.203.222:9200/")
# es全量同步数据
@left_blue.route('/tb')
def tb():
    res = db.session.execute("select * from (select * from need where status=5 union all select * from need1 where status=5 union all select * from need2 where status=5) as a order by code asc")
    if res:
        lst = []
        for i in list(res):
            lst.append(i.code)
            es.index(index='zbj_needs',doc_type="k",body={
                'code': str(i.code),
                'title': i.title,
                "money": i.money,
                "described": i.described,
                "closeid": i.closeid,
                "userid": i.userid
            })
        key = "zbj_needs"
        r.str_add(key,lst[-1])
        return jsonify({"code": 200, "msg": "同步完成"})
    else:
        return jsonify({"code":400,"msg":"没有找到数据"})

# 查询
import math
@left_blue.route('/inquire')
def inquire():
    title = request.args.get("title")
    page = request.args.get("page")
    page_size = request.args.get("page_size")
    start = math.ceil((int(page) - 1) * int(page_size))
    sql = db.session.execute("select count(*) as a from (select * from need where status=5 union all select * from need1 where status=5 union all select * from need2 where status=5) as a")
    total = []
    for i in sql:
        total.append(i.a)
    if title:
        res = {
            "query":{
                "match":{"title":title}
            },
            "from":start,
            "size":page_size,
        }
        res1 = es.search(index="zbj_needs",body=res)
        lst = []
        for i in res1['hits']['hits']:
            i["_source"]["code"] = str(i["_source"]["code"])
            lst.append(i["_source"])
        return jsonify({"code": 200, "data":lst,"total":total})
    else:
        res = {
            "query": {
                "match_all": {}
            },
            "from": start,
            "size": page_size,
        }
        res1 = es.search(index="zbj_needs", body=res)
        lst = []
        for i in res1['hits']['hits']:
            i["_source"]["code"] = str(i["_source"]["code"])
            lst.append(i["_source"])
        return jsonify({"code": 200, "data": lst, "total": total})





















